/*
 * @lc app=leetcode.cn id=671 lang=cpp
 *
 * [671] 二叉树中第二小的节点
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    int min1 = -1;  // 记录最小的值
    int min2 = -1;  // 记录第二小的值

    int findSecondMinimumValue(TreeNode *root) {
        dfs(root);
        return min2;
    }

    // 返回的是当前节点的值
    int dfs(TreeNode *root) {
        int value = 0;

        // 第一种情况，没有子节点
        if (root->left == nullptr && root->right == nullptr){
            value = root->val;
        } 

        // 第二种情况，有两个子节点
        if (root->left != nullptr && root->right != nullptr) {
            int left = dfs(root->left);
            int right = dfs(root->right);
            value = min(left, right);
        }

        // 更新最小值
        if (min1 == -1 || value < min1) {
            min2 = min1;
            min1 = value;
        } else if ((value > min1) && (min2 == -1 || value < min2)) {
            min2 = value;
        }

        return value;
    }
};
// @lc code=end
